package com.zbw.printlibrary.printSub;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;


import com.newland.pospp.openapi.manager.INewlandCashDrawerManager;
import com.newland.pospp.openapi.manager.INewlandManagerCallback;
import com.newland.pospp.openapi.manager.INewlandOpenDrawerCallback;
import com.newland.pospp.openapi.manager.INewlandPrintCallback;
import com.newland.pospp.openapi.manager.INewlandPrinterManager;
import com.newland.pospp.openapi.manager.ServiceManagerType;
import com.newland.pospp.openapi.manager.ServiceManagersHelper;
import com.newland.pospp.openapi.model.CapabilityProvider;
import com.newland.pospp.openapi.model.NewlandError;
import com.newland.pospp.openapi.model.PrinterScript;
import com.newland.pospp.openapi.model.printer.Align;
import com.newland.pospp.openapi.model.printer.FontSize;
import com.newland.pospp.openapi.model.printer.Image;
import com.newland.pospp.openapi.model.printer.Text;
import com.newland.pospp.openapi.model.printer.Texts;
import com.zbw.printlibrary.bean.AttributeBean;
import com.zbw.printlibrary.printConnector.IPrintCallBack;
import com.zbw.printlibrary.printConnector.PrinterControlCommon;
import com.zbw.printlibrary.util.AppParamsUtils;
import com.zbw.printlibrary.util.JsonAnalysisUtil;
import com.zbw.printlibrary.util.PrintThreadPoolManager;


import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.util.LinkedHashMap;
import java.util.List;


/**
 * Created by cyj on 2019-07-25.
 * CposX5 新大陆打印机
 */

public class PrintCPosX5 extends PrinterControlCommon {
    private Context mContext;
    private IPrintCallBack mCallBack;
    private CapabilityProvider mProvider;
    private ServiceManagersHelper mHelper;
    private INewlandPrinterManager manager;
    public String selectPrinter;

    public PrintCPosX5(@NonNull Context context, IPrintCallBack callback) {
        mContext = context;
        this.mCallBack = callback;
    }

    @Override
    public void connectPrinter() {
        mHelper = new ServiceManagersHelper(mContext);
        mHelper.getPrinterManager(new INewlandManagerCallback.INewlandPrinterCallback() {
            @Override
            public void onSuccess(INewlandPrinterManager iNewlandPrinterManager, CapabilityProvider capabilityProvider) {
                mProvider = capabilityProvider;
                manager = iNewlandPrinterManager;
                mCallBack.onConnect("找到支持的打印服务", true);
            }

            @Override
            public void onError(NewlandError newlandError) {
                mCallBack.onConnect("未找到支持的打印服务", false);
            }
        });
    }

    @Override
    public void disConnectPrinter() {
        try {
            if (mHelper != null && mProvider != null) {
                mHelper.disconnectService(ServiceManagerType.PRINTER);
            }

        } catch (Exception e) {
            e.printStackTrace();
            mCallBack.onDisConnect("断开失败", false);
        }

    }

    @Override
    public void printTest(final List<String> list) {
        if (null == manager) {
            Toast.makeText(mContext, "未找到支持的打印服务", Toast.LENGTH_SHORT).show();
            return;
        }
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    PrinterScript printerScript = getPrintScript(list);
                    // AppContext.instance.selectPrinter 如果为null则调默认打印机进行打印
                    manager.print(selectPrinter, printerScript, new INewlandPrintCallback() {
                        @Override
                        public void onSuccess() {
                            mCallBack.onPrintResult(true);
                        }

                        @Override
                        public void onError(final NewlandError newlandError) {
                            String reason = newlandError.getReason();
                            Log.d("tag", "onError: " + reason);
                            mCallBack.onPrintResult(false);
                        }
                    });

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public void printString(final List<AttributeBean> testList) {
        if (null == manager) {
            Toast.makeText(mContext, "未找到支持的打印服务", Toast.LENGTH_SHORT).show();
            return;
        }
        PrintThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    PrinterScript printerScript = getPrintText(testList);
                    // AppContext.instance.selectPrinter 如果为null则调默认打印机进行打印
                    manager.print(selectPrinter, printerScript, new INewlandPrintCallback() {
                        @Override
                        public void onSuccess() {
                            mCallBack.onPrintResult(true);
                        }

                        @Override
                        public void onError(final NewlandError newlandError) {
                            String reason = newlandError.getReason();
                            Log.d("tag", "onError: " + reason);
                            mCallBack.onPrintResult(false);
                        }
                    });

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    mCallBack.onPrintResult(false);
                    e.printStackTrace();
                }

            }
        });
    }

    private PrinterScript getPrintScript(List<String> list) {

        PrinterScript printerScript = new PrinterScript();
        printerScript.addText(normalTextSize(list.get(0), Align.CENTER));
        if (!list.get(1).isEmpty()) {
            printerScript.addText(normalText(list.get(1), Align.CENTER));
        }
        for (int i = 2; i < list.size(); i++) {
            if (list.get(i).contains(". ") && !list.get(i).contains(":")) {
                printerScript.addText(normalTextSize(list.get(i), Align.LEFT));
            } else {
                printerScript.addText(normalText(list.get(i)));
            }
        }
        printerScript.addFeedLine(5);
        printerScript.addCutPaper(0);

        return printerScript;
    }

    private PrinterScript getPrintText(List<AttributeBean> list) {

        PrinterScript printerScript = new PrinterScript();
        for (int i = 0; i < list.size(); i++) {
            if (!list.get(i).getContext().isEmpty()) {
                Align align = null;
                switch (list.get(i).getFont_gray()) {
                    case 0:
                        align = Align.LEFT;
                        break;
                    case 1:
                        align = Align.CENTER;
                        break;
                    case 2:
                        align = Align.RIGHT;
                        break;
                }
                if (1 == list.get(i).getContext_type()) {
                    String imageUri = "base64://" + bitmapToBase(list.get(i).getBitmap());
                    Image image = getImage(false);
                    image.setPath(imageUri);
                    printerScript.addImage(image);
                } else {
                    if (list.get(i).getFont_size() == 2) {
                        printerScript.addText(normalTextSize(list.get(i).getContext(), align));
                    } else {
                        printerScript.addText(normalText(list.get(i).getContext(), align));
                    }
                }

            }
        }
        printerScript.addFeedLine(5);
        printerScript.addCutPaper(0);

        return printerScript;
    }

    @Override
    public void printStringAndBitmap(List<String> testList, LinkedHashMap<Integer, Bitmap> bitmapHashMap) {
        printTest(testList);
    }

    @Override
    public void blueConnect(String address) {

    }

    @Override
    public void disBlueConnect() {

    }


    @Override
    public void openMoneyBox() {
        casherBox();
    }

    @Override
    public boolean isConnected() {
        if (manager == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 开钱箱,拉卡拉
     */
    public void casherBox() {
        mHelper.getCashDrawerManager(new INewlandManagerCallback.INewlandCashDrawerCallback() {
            @Override
            public void onSuccess(INewlandCashDrawerManager manager, CapabilityProvider provider) {
                manager.openDrawer(new INewlandOpenDrawerCallback() {
                    @Override
                    public void onSuccess() {
                    }

                    @Override
                    public void onError(NewlandError newlandError) {
                        Log.e("openDrawer", "code == " + newlandError.getCode());
                        Toast.makeText(mContext, newlandError.getReason(mContext), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onError(NewlandError newlandError) {
                Log.e("getCashDrawerManager", "code == " + newlandError.getCode());
                Toast.makeText(mContext, newlandError.getReason(mContext), Toast.LENGTH_SHORT).show();
            }
        });
    }


    public static String getFontPath() {
        return "/mnt/sdcard/simsun.ttc";
    }

    private Text smallText(String txt) {
        return new Text().setEnFontSize(FontSize.SMALL).setChFontSize(FontSize.SMALL).setTxt(txt);
    }

    private Text normalText(String txt) {
        return new Text().setTxt(txt);
    }

    private Text normalText(String txt, Align align) {
        return new Text().setTxt(txt).setAlign(align);
    }

    private Text normalTextSize(String txt, Align align) {
        return new Text().setTxt(txt).setAlign(align).setChFontSize(FontSize.LARGE);
    }

    private Text normalText(String txt, int offset) {
        return new Text().setTxt(txt).setOffset(offset);
    }

    private Text largeText(String txt) {
        return new Text().setEnFontSize(FontSize.LARGE).setChFontSize(FontSize.LARGE).setTxt(txt);
    }

    private Texts normalTexts(String txt, int offset) {
        return new Texts().setTxt(txt).setOffset(offset);
    }

    private Texts normalTexts(String txt, Align align) {
        return new Texts().setTxt(txt).setAlign(align);
    }

    private Texts normalTexts(String txt) {
        return new Texts().setTxt(txt);
    }

    /**
     * Bitmap转Base64
     */
    private String bitmapToBase(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    public static Image getImage(boolean isDefault) {
        Image image = null;
        String imgSetting = AppParamsUtils.getInstance().getPrintImg();
        if (isDefault || TextUtils.isEmpty(imgSetting)) {
            image = new Image();
            image.setAlign(Align.LEFT);
            image.setPath("assets://print_logo.png");
        } else {
            try {
                image = JsonAnalysisUtil.getObjectByString(imgSetting, Image.class);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return image;
    }

    @Override
    public void printString(List<AttributeBean> testList, int width) {

    }

}
